package com.bosssoft.promotions.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bosssoft.promotions.dao.PromotionsDao;
import com.bosssoft.promotions.domain.po.Promotions;
import com.bosssoft.promotions.service.PromotionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

@Service
public class PromotionImpl implements PromotionService {
    @Autowired
    private PromotionsDao promotionsDao ;

    @Override
    public Map<String, BigDecimal> getDeposit(String promotionId, String price) {
        BigDecimal bPrice = new BigDecimal(price);
        Promotions promotions = promotionsDao.selectById(promotionId);
        // 获取商品参加的具体活动列表（promotion是一个json数组）
        JSONArray promotionArray = JSONArray.parseArray(promotions.getPromotion());
        // 获取 threshold的值（门槛价格）
        for (int i = 0; i < promotionArray.size(); i++){

            //获取折扣率
            Object zhekoulvObject = promotionArray.getJSONObject(i).get("deposit_discount");
            // 如果折扣率存在于当前数组，说明抵扣率也存在
            if(null != zhekoulvObject){
                BigDecimal zhekoulv = new BigDecimal(zhekoulvObject.toString());
                BigDecimal dikoulv = new BigDecimal(promotionArray.getJSONObject(i).get("reduction_rate").toString());

                //设置定金价格
                BigDecimal dingjin = zhekoulv.multiply(bPrice);
                //计算定金抵扣后的价格
                BigDecimal zhekouhouPrice = bPrice.subtract(dingjin.multiply(dikoulv));
                //放入map
                Map<String,BigDecimal> map = new HashMap<>();
                map.put("dingjin",dingjin);
                map.put("zhekouhouPrice",zhekouhouPrice);

                //返回存储了定金和折扣后价格的map
                return map;
            }
        }
        //啥也没有 ，没查到相应的定金活动，不返回东西
        return null;
    }

    @Override
    public BigDecimal getDiscount(String promotionId,String price) {
        BigDecimal bPrice = new BigDecimal(price);
        Promotions promotions = promotionsDao.selectById(promotionId);

        JSONArray promotionArray = JSONArray.parseArray(promotions.getPromotion());
        for (int i = 0; i < promotionArray.size(); i++){
            Object discountObject = promotionArray.getJSONObject(i).get("discount");
            // 如果 套装存在于当前数组, 就存到map中
            if(null != discountObject){
                BigDecimal bDiscount = new BigDecimal(discountObject.toString());
                BigDecimal currentPrice = bPrice.multiply(bDiscount);
                return currentPrice;
            }
        }
        return null;
        // 获取 discount的值（折扣率）
//        Object discount = promotion.get("discount");
//        BigDecimal bDiscount = new BigDecimal(discount.toString());
//        BigDecimal currentPrice = bPrice.multiply(bDiscount);
//        return currentPrice;
    }

    public BigDecimal getSuit(String promotionId, List<String> ids) {

        BigDecimal total = new BigDecimal(Math.pow(2,40));


        Map<Integer, JSONObject> map = new HashMap<>();

        Promotions promotions = promotionsDao.selectById(promotionId);
        // 获取商品参加的具体活动列表（promotion是一个json数组）
        JSONArray promotionArray = JSONArray.parseArray(promotions.getPromotion());

        // 获取套装信息
        for (int i = 0; i < promotionArray.size(); i++){
            Object taozhuangObject = promotionArray.getJSONObject(i).get("suit_id");
            // 如果 套装存在于当前数组, 就存到map中
            if(null != taozhuangObject){
                map.put(i,promotionArray.getJSONObject(i));
            }
        }

        Set<Map.Entry<Integer,JSONObject>> entries=map.entrySet();
        for (Map.Entry entry:entries){
            if( isSuit(entry,ids)!=null){
                List<String> shop = isSuit(entry,ids);
                for(String s:shop) {
                    ids.remove(s);
                }
                total = total.compareTo(get(map,ids))==-1 ? total :get(map,ids);
                for(String s:shop) {
                    ids.add(s);
                }
            }
        }

        return total;
    }


    public BigDecimal get(Map<Integer, JSONObject> map, List<String> ids) {
        BigDecimal total = new BigDecimal(Math.pow(2,40));

        Set<Map.Entry<Integer,JSONObject>> entries=map.entrySet();
        for (Map.Entry entry:entries){
            if( isSuit(entry,ids)!=null){
                List<String> shop = isSuit(entry,ids);
                for(String s:shop) {
                    ids.remove(s);
                }
                total = total.compareTo(get(map,ids))==-1 ? total :get(map,ids);
                for(String s:shop) {
                    ids.add(s);
                }
            }
        }
        return total;
    }


    public List<String> isSuit(Map.Entry<Integer,JSONObject> entry,List<String> ids){

        List<String> shop = new ArrayList<>();

        for(int i = 0;i<entry.getValue().size();i++) {
            Iterator iterator= entry.getValue().values().iterator();
            while(iterator.hasNext()){
                String key = (String) iterator.next();
                //当json的key不是id或者价格的时候才判断是否存在于ids中
                if(!key.equals("suit_price") && !key.equals("suit_id")) {
                    if (!ids.contains(key)) {
                        return null;
                    } else {
                        shop.add(key);
                    }
                }
            }
        }
        return shop;
    }

    @Override
    public BigDecimal getFullReduction(String promotionId, String price) {
        // 选中商品的总价
        BigDecimal total = new BigDecimal(price);

        Promotions promotions = promotionsDao.selectById(promotionId);
        // 获取商品参加的具体活动列表（promotion是一个json数组）
        JSONArray promotionArray = JSONArray.parseArray(promotions.getPromotion());
        // 获取 threshold的值（门槛价格）
        for (int i = 0; i < promotionArray.size(); i++){
            Object thresholdObject = promotionArray.getJSONObject(i).get("threshold");
            // 如果门槛存在于当前数组
            if(null != thresholdObject){
                BigDecimal threshold = new BigDecimal(thresholdObject.toString());
                BigDecimal discount = new BigDecimal(promotionArray.getJSONObject(i).get("discount_price").toString());
                //判断价格是否到达门槛价
                if(total.compareTo(threshold)==1){
                    BigDecimal currentPrice = total.subtract(discount);
                    return currentPrice;
                }
                //未达到门槛的返回结果
                else {
                    return total;
                }
            }
        }
        // 没找到threshold的值（门槛值）就返回原价
        return total;
    }



    @Override
    public List<String> justice(String promotionId, List<String> ids){
        Promotions promotions = promotionsDao.selectById(promotionId);
        // 获取商品参加的具体活动列表（promotion是一个json数组）
        JSONArray promotionArray = JSONArray.parseArray(promotions.getPromotion());
        List<String> style = new ArrayList<>();
        // 获取 threshold的值（门槛价格）
        for (int i = 0; i < promotionArray.size(); i++) {
            Object thresholdObject = promotionArray.getJSONObject(i).get("threshold");
            Object zhekoulvObject = promotionArray.getJSONObject(i).get("deposit_discount");
            Object discountObject = promotionArray.getJSONObject(i).get("discount");
            // 如果门槛存在于当前数组
            if (null != thresholdObject) {
                style.add("满减活动");
            } else if (null != zhekoulvObject) {
                style.add("定金活动");
            } else if (null != discountObject) {
                style.add("打折活动");
            }
        }
        return style;
    }


    public Boolean getBoolean(String promotionId, List<String> ids) {

        BigDecimal total = new BigDecimal(Math.pow(2,40));
        BigDecimal total1 = new BigDecimal(Math.pow(2,40));

        Map<Integer, JSONObject> map = new HashMap<>();

        Promotions promotions = promotionsDao.selectById(promotionId);
        // 获取商品参加的具体活动列表（promotion是一个json数组）
        JSONArray promotionArray = JSONArray.parseArray(promotions.getPromotion());

        // 获取套装信息
        for (int i = 0; i < promotionArray.size(); i++){
            Object taozhuangObject = promotionArray.getJSONObject(i).get("taozhuangID");
            // 如果 套装存在于当前数组, 就存到map中
            if(null != taozhuangObject){
                map.put(i,promotionArray.getJSONObject(i));
            }
        }
        Set<Map.Entry<Integer,JSONObject>> entries=map.entrySet();
        for (Map.Entry entry:entries){
            if( isSuit(entry,ids)!=null){
                List<String> shop = isSuit(entry,ids);
                for(String s:shop) {
                    ids.remove(s);
                }
                total = total.compareTo(get(map,ids))==-1 ? total :get(map,ids);
                for(String s:shop) {
                    ids.add(s);
                }
            }
        }
        return !(total.compareTo(total1)==0);
    }
}
